import { Cell, CellView, Edge, Graph, type Nilable } from '@antv/x6'

export const initGraph = (container: HTMLDivElement, rect: DOMRect, options?: any) => {
  // 初始化画布
  const _options = Object.assign({}, {
    container: container,
    grid: {
      size: 5
    },
    autoResize: true,
    width: rect.width,
    height: rect.height,
    mousewheel: {
      enabled: true,
      modifiers: ['ctrl']
    },
    // panning: {
    //   enabled: true,
    //   modifiers:['space']
    // },
    connecting: {
      snap: {
        radius: 100
      },
      allowBlank: false,
      allowLoop: false,
      allowEdge: false,
      router: {
        name: 'manhattan',
        args: {
          excludeTerminals: ['source', 'target'],
          startDirections: ['right'],
          endDirections: ['left'],
          padding: 50
        }
      },
      createEdge: function(this: Graph,
                           args: {
                             sourceCell: Cell
                             sourceView: CellView
                             sourceMagnet: Element
                           }): Nilable<Edge> | void {
        console.log(args)
        return this.createEdge({
          shape: 'pipeline'
        }).setZIndex(-Math.round(Math.random() * 100))
      }
    }
  }, options)
  return new Graph(_options)
}

export const downloadFile = async function(data: BlobPart, fileName: string) {
  const blob = new Blob([data])
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href
  downloadElement.download = fileName // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}
